import React, { useEffect, useState, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Avatar,
  message,
  Row,
  Col,
  Statistic,
  Typography,
  Tooltip,
  Modal,
  Form,
  Switch,
  DatePicker,
  Popconfirm,
  Badge,
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  UserAddOutlined,
  ExportOutlined,
  ReloadOutlined,
  UserOutlined,
  CrownOutlined,
  LockOutlined,
  UnlockOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TableRowSelection } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;

interface User {
  id: string;
  username: string;
  email: string;
  phone?: string;
  avatar?: string;
  nickname?: string;
  gender: 'male' | 'female' | 'unknown';
  birthday?: string;
  status: 'active' | 'inactive' | 'banned';
  role: 'admin' | 'user' | 'vip' | 'merchant';
  level: number;
  points: number;
  balance: number;
  totalOrders: number;
  totalSpent: number;
  lastLoginAt?: string;
  createdAt: string;
  updatedAt: string;
}

interface UserListState {
  users: User[];
  loading: boolean;
  total: number;
  current: number;
  pageSize: number;
  selectedRowKeys: React.Key[];
  searchKeyword: string;
  filters: {
    status: string;
    role: string;
    level: string;
    dateRange: [string, string] | null;
  };
}

const UserList: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 状态管理
  const [state, setState] = useState<UserListState>({
    users: [],
    loading: false,
    total: 0,
    current: 1,
    pageSize: 10,
    selectedRowKeys: [],
    searchKeyword: '',
    filters: {
      status: '',
      role: '',
      level: '',
      dateRange: null,
    },
  });

  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);

  // 设置面包屑
  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '用户管理' },
      { title: '用户列表' },
    ]));
  }, [dispatch]);

  // 加载用户数据
  const loadUsers = useCallback(async () => {
    try {
      setState(prev => ({ ...prev, loading: true }));

      // 模拟用户数据
      const mockUsers: User[] = [
        {
          id: '1',
          username: 'zhangsan',
          email: 'zhangsan@example.com',
          phone: '13800138000',
          avatar: 'https://via.placeholder.com/40x40',
          nickname: '张三',
          gender: 'male',
          birthday: '1990-01-01',
          status: 'active',
          role: 'user',
          level: 3,
          points: 1500,
          balance: 299.50,
          totalOrders: 25,
          totalSpent: 12500,
          lastLoginAt: '2024-01-20T10:30:00Z',
          createdAt: '2023-06-15T08:00:00Z',
          updatedAt: '2024-01-20T10:30:00Z',
        },
        {
          id: '2',
          username: 'lisi',
          email: 'lisi@example.com',
          phone: '13900139000',
          nickname: '李四',
          gender: 'female',
          status: 'active',
          role: 'vip',
          level: 5,
          points: 3200,
          balance: 1299.00,
          totalOrders: 58,
          totalSpent: 35800,
          lastLoginAt: '2024-01-19T15:20:00Z',
          createdAt: '2023-03-20T10:00:00Z',
          updatedAt: '2024-01-19T15:20:00Z',
        },
        {
          id: '3',
          username: 'wangwu',
          email: 'wangwu@example.com',
          phone: '13700137000',
          nickname: '王五',
          gender: 'male',
          status: 'banned',
          role: 'user',
          level: 1,
          points: 50,
          balance: 0,
          totalOrders: 2,
          totalSpent: 199,
          lastLoginAt: '2024-01-10T09:15:00Z',
          createdAt: '2024-01-05T14:30:00Z',
          updatedAt: '2024-01-15T11:45:00Z',
        },
        {
          id: '4',
          username: 'admin',
          email: 'admin@example.com',
          nickname: '管理员',
          gender: 'unknown',
          status: 'active',
          role: 'admin',
          level: 10,
          points: 0,
          balance: 0,
          totalOrders: 0,
          totalSpent: 0,
          lastLoginAt: '2024-01-20T16:00:00Z',
          createdAt: '2023-01-01T00:00:00Z',
          updatedAt: '2024-01-20T16:00:00Z',
        },
      ];

      setState(prev => ({
        ...prev,
        users: mockUsers,
        total: mockUsers.length,
        loading: false,
      }));
    } catch (error) {
      message.error('加载用户数据失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  }, []);

  // 初始加载
  useEffect(() => {
    loadUsers();
  }, [loadUsers]);

  // 获取状态标签
  const getStatusTag = (status: string) => {
    const statusConfig = {
      active: { color: 'green', text: '正常' },
      inactive: { color: 'orange', text: '未激活' },
      banned: { color: 'red', text: '已封禁' },
    };
    const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 获取角色标签
  const getRoleTag = (role: string) => {
    const roleConfig = {
      admin: { color: 'red', text: '管理员', icon: <CrownOutlined /> },
      merchant: { color: 'blue', text: '商家', icon: <UserOutlined /> },
      vip: { color: 'gold', text: 'VIP用户', icon: <CrownOutlined /> },
      user: { color: 'default', text: '普通用户', icon: <UserOutlined /> },
    };
    const config = roleConfig[role as keyof typeof roleConfig] || { color: 'default', text: role, icon: <UserOutlined /> };
    return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
  };

  // 处理用户状态切换
  const handleStatusToggle = async (userId: string, newStatus: string) => {
    try {
      // await UserService.updateUserStatus(userId, newStatus);
      message.success('用户状态更新成功');
      loadUsers();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  // 删除用户
  const handleDeleteUser = async (userId: string) => {
    try {
      // await UserService.deleteUser(userId);
      message.success('用户删除成功');
      loadUsers();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 编辑用户
  const handleEditUser = (user: User) => {
    setEditingUser(user);
    form.setFieldsValue({
      username: user.username,
      email: user.email,
      phone: user.phone,
      nickname: user.nickname,
      status: user.status,
      role: user.role,
    });
    setEditModalVisible(true);
  };

  // 保存用户编辑
  const handleSaveUser = async (values: any) => {
    try {
      if (editingUser) {
        // await UserService.updateUser(editingUser.id, values);
        message.success('用户信息更新成功');
      }
      setEditModalVisible(false);
      loadUsers();
    } catch (error) {
      message.error('保存失败');
    }
  };

  // 行选择
  const rowSelection: TableRowSelection<User> = {
    selectedRowKeys: state.selectedRowKeys,
    onChange: (selectedRowKeys) => {
      setState(prev => ({ ...prev, selectedRowKeys }));
    },
  };

  // 表格列定义
  const columns: ColumnsType<User> = [
    {
      title: '用户信息',
      key: 'userInfo',
      width: 200,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar
            src={record.avatar}
            size={40}
            style={{ marginRight: 12 }}
          >
            {record.nickname?.[0] || record.username[0]}
          </Avatar>
          <div>
            <div style={{ fontWeight: 500 }}>
              {record.nickname || record.username}
            </div>
            <div style={{ fontSize: 12, color: '#666' }}>
              ID: {record.id}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '联系方式',
      key: 'contact',
      width: 180,
      render: (_, record) => (
        <div>
          <div style={{ marginBottom: 4 }}>{record.email}</div>
          {record.phone && (
            <div style={{ fontSize: 12, color: '#666' }}>
              {record.phone}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      filters: [
        { text: '正常', value: 'active' },
        { text: '未激活', value: 'inactive' },
        { text: '已封禁', value: 'banned' },
      ],
      render: (status) => getStatusTag(status),
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      width: 120,
      filters: [
        { text: '管理员', value: 'admin' },
        { text: '商家', value: 'merchant' },
        { text: 'VIP用户', value: 'vip' },
        { text: '普通用户', value: 'user' },
      ],
      render: (role) => getRoleTag(role),
    },
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      sorter: (a, b) => a.level - b.level,
      render: (level) => (
        <Badge count={level} style={{ backgroundColor: '#52c41a' }} />
      ),
    },
    {
      title: '积分',
      dataIndex: 'points',
      key: 'points',
      width: 100,
      sorter: (a, b) => a.points - b.points,
      render: (points) => points.toLocaleString(),
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 100,
      sorter: (a, b) => a.balance - b.balance,
      render: (balance) => `¥${balance.toFixed(2)}`,
    },
    {
      title: '订单统计',
      key: 'orderStats',
      width: 120,
      render: (_, record) => (
        <div>
          <div>{record.totalOrders} 单</div>
          <div style={{ fontSize: 12, color: '#666' }}>
            ¥{record.totalSpent.toLocaleString()}
          </div>
        </div>
      ),
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginAt',
      key: 'lastLoginAt',
      width: 150,
      sorter: (a, b) => new Date(a.lastLoginAt || 0).getTime() - new Date(b.lastLoginAt || 0).getTime(),
      render: (lastLoginAt) => lastLoginAt ? new Date(lastLoginAt).toLocaleString() : '-',
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => navigate(`/users/${record.id}`)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEditUser(record)}
            />
          </Tooltip>
          <Tooltip title={record.status === 'banned' ? '解封' : '封禁'}>
            <Button
              type="text"
              size="small"
              icon={record.status === 'banned' ? <UnlockOutlined /> : <LockOutlined />}
              onClick={() => handleStatusToggle(
                record.id,
                record.status === 'banned' ? 'active' : 'banned'
              )}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                size="small"
                icon={<DeleteOutlined />}
                danger
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="用户总数"
              value={state.total}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="活跃用户"
              value={state.users.filter(u => u.status === 'active').length}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="VIP用户"
              value={state.users.filter(u => u.role === 'vip').length}
              valueStyle={{ color: '#faad14' }}
              prefix={<CrownOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="封禁用户"
              value={state.users.filter(u => u.status === 'banned').length}
              valueStyle={{ color: '#f50' }}
              prefix={<LockOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Space>
              <Search
                placeholder="搜索用户名、邮箱、手机号..."
                style={{ width: 300 }}
                onSearch={(value) => setState(prev => ({ ...prev, searchKeyword: value }))}
                enterButton={<SearchOutlined />}
              />
              <Select
                placeholder="用户状态"
                style={{ width: 120 }}
                allowClear
                onChange={(value) => setState(prev => ({
                  ...prev,
                  filters: { ...prev.filters, status: value || '' }
                }))}
              >
                <Option value="active">正常</Option>
                <Option value="inactive">未激活</Option>
                <Option value="banned">已封禁</Option>
              </Select>
              <Select
                placeholder="用户角色"
                style={{ width: 120 }}
                allowClear
                onChange={(value) => setState(prev => ({
                  ...prev,
                  filters: { ...prev.filters, role: value || '' }
                }))}
              >
                <Option value="admin">管理员</Option>
                <Option value="merchant">商家</Option>
                <Option value="vip">VIP用户</Option>
                <Option value="user">普通用户</Option>
              </Select>
            </Space>
          </Col>
          <Col>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={loadUsers}>
                刷新
              </Button>
              <Button icon={<ExportOutlined />}>
                导出
              </Button>
              <Button type="primary" icon={<UserAddOutlined />}>
                添加用户
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 用户表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={state.users}
          rowKey="id"
          rowSelection={rowSelection}
          loading={state.loading}
          pagination={{
            current: state.current,
            pageSize: state.pageSize,
            total: state.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          scroll={{ x: 1400 }}
          size="middle"
        />
      </Card>

      {/* 编辑用户模态框 */}
      <Modal
        title="编辑用户"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveUser}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="昵称"
                name="nickname"
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="邮箱"
                name="email"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="手机号"
                name="phone"
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="状态"
                name="status"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select>
                  <Option value="active">正常</Option>
                  <Option value="inactive">未激活</Option>
                  <Option value="banned">已封禁</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="角色"
                name="role"
                rules={[{ required: true, message: '请选择角色' }]}
              >
                <Select>
                  <Option value="admin">管理员</Option>
                  <Option value="merchant">商家</Option>
                  <Option value="vip">VIP用户</Option>
                  <Option value="user">普通用户</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default UserList;
